#!usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import logging
import os
import logging.config
import re

import requests
from requests.adapters import HTTPAdapter
from werkzeug import security
from flask import flash as flask_flash, url_for, current_app
from math import ceil
import random

from spider.lib.crypto import IdCipher
from spider.utils.timeutil import get_now, datetime_to_str_time, get_now_str

MOBILE_NUM_RE = r'(^1)([35]\d|47|[78][012356789])(\d{8}$)'  # 验证手机号正则

crypto_key = '!y@h%d^d'  # 加密key
id_cipher = IdCipher(crypto_key)
id_encrypt = id_cipher.encrypt
id_decrypt = id_cipher.decrypt


def get_default_logger():
    logger = logging.getLogger("icp")
    return logger


logger = get_default_logger()


def logger_config():
    log_dir = '/tmp/icp_check_logs/'
    # log_dir = 'C:/www/icp_spider/'
    log_file = datetime.datetime.now().strftime("%Y-%m-%d") + ".log"
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "simple": {
                'format': '%(asctime)s [%(name)s:%(lineno)d] [%(levelname)s] - 【%(message)s】'
            },
            'default': {
                'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(levelname)s] - 【%(message)s】'
            },
        },

        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "stream": "ext://sys.stdout"
            },
            "default": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "simple",
                "filename": os.path.join(log_dir, log_file),
                'mode': 'w+',
                "maxBytes": 1024 * 1024 * 5,  # 5 MB
                "backupCount": 20,
                "encoding": "utf8"
            },
        },
        "loggers": {
            "default": {
                'handlers': ['console', 'default'],
                'level': "INFO",
                'propagate': False
            }
        },
    }


def get_logger():
    logging.config.dictConfig(logger_config())
    return logging.getLogger("default")


def get_rand_no():
    return random.choice([1, 2, 3])


def simple_log(content):
    print('\r\n===============')
    print(content)
    print('===============\r\n')


def init_rsyslog(filename):
    logger = logging.getLogger()
    hdlr = logging.FileHandler(filename)
    formatter = logging.Formatter(u'[%(asctime)s]%(levelname)-8s"%(message)s"', '%Y-%m-%d %a %H:%M:%S')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    return logger

def get_requests(max_retries=3):
    r = requests.Session()
    r.mount('http://', HTTPAdapter(max_retries=max_retries))
    r.mount('https://', HTTPAdapter(max_retries=max_retries))
    return r


def flash(message, level='info', category='message'):
    flask_flash({'msg': message, 'level': level}, category=category)


class Pagination(object):

    def __init__(self, page, per_page, total_count, endpoint=None, params=None):
        self.params = params
        self.endpoint = endpoint
        self.page = page
        self.per_page = per_page
        self.total_count = total_count

    @property
    def pages(self):
        return int(ceil(self.total_count / float(self.per_page)))

    @property
    def has_prev(self):
        return self.page > 1

    @property
    def has_next(self):
        return self.page < self.pages

    def iter_pages(self, left_edge=2, left_current=2,
                   right_current=5, right_edge=2):
        last = 0
        for num in xrange(1, self.pages + 1):
            if num <= left_edge or \
                    (num > self.page - left_current - 1 and
                     num < self.page + right_current) or \
                    num > self.pages - right_edge:
                if last + 1 != num:
                    yield None
                yield num
                last = num


def create_password(raw):
    password = '%s%s' % (raw, current_app.config['PASSWORD_SECRET'])
    return security.generate_password_hash(password)


def check_password(raw, user_password):
    pass_check = '%s%s' % (raw, current_app.config['PASSWORD_SECRET'])
    return security.check_password_hash(user_password, pass_check)


def generate_code(length=6):
    return ''.join([str(random.randint(0, 9)) for i in range(length)])


def generate_sn():
    time_str = datetime_to_str_time(get_now(), format_str='%Y%m%d%H%M%S')
    sign = ''
    for num in range(11):
        sign += str(num)
    return time_str + sign


def get_suffix(domain):
    suffix = [
        '.ac.cn',
        '.ah.cn',
        '.bj.cn',
        '.com.cn',
        '.cq.cn',
        '.fj.cn',
        '.gd.cn',
        '.gov.cn',
        '.gs.cn',
        '.gx.cn',
        '.gz.cn',
        '.ha.cn',
        '.hb.cn',
        '.he.cn',
        '.hi.cn',
        '.hk.cn',
        '.hl.cn',
        '.hn.cn',
        '.jl.cn',
        '.js.cn',
        '.jx.cn',
        '.ln.cn',
        '.mo.cn',
        '.net.cn',
        '.nm.cn',
        '.nx.cn',
        '.org.cn',
    ]
    ends_with = False
    res = ''
    for s in suffix:
        if domain.endswith(s) is True:
            ends_with = True
            res = s
            break
    if ends_with is True:
        return res
    try:
        match_res = re.match(r'.*(\..{2,3})', domain)
        res = match_res[1]
    except:
        pass
    return res
